<?php
session_start();
require_once '../classes/Database.php';
require_once '../classes/OrderManager.php';
require_once '../classes/SettingsHelper.php';

// 检查登录状态
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$db = Database::getInstance();
$orderManager = new OrderManager();

// 获取支付记录
$sql = "SELECT pl.*, o.product_id, o.total_amount, o.contact_info, p.name as product_name 
        FROM payment_logs pl 
        LEFT JOIN orders o ON pl.order_no = o.order_no 
        LEFT JOIN products p ON o.product_id = p.id 
        ORDER BY pl.created_at DESC 
        LIMIT 100";
$paymentLogs = $db->query($sql);

// 获取支付统计
$sql = "SELECT 
        COUNT(*) as total_payments,
        COUNT(DISTINCT order_no) as unique_orders,
        SUM(CASE WHEN action = 'create' THEN 1 ELSE 0 END) as create_count,
        SUM(CASE WHEN action = 'notify' THEN 1 ELSE 0 END) as notify_count,
        SUM(CASE WHEN action = 'return' THEN 1 ELSE 0 END) as return_count
        FROM payment_logs";
$paymentStats = $db->query($sql);
$paymentStats = !empty($paymentStats) ? $paymentStats[0] : [];

// 搜索功能
$searchKeyword = $_GET['search'] ?? '';
if ($searchKeyword) {
    $sql = "SELECT pl.*, o.product_id, o.total_amount, o.contact_info, p.name as product_name 
            FROM payment_logs pl 
            LEFT JOIN orders o ON pl.order_no = o.order_no 
            LEFT JOIN products p ON o.product_id = p.id 
            WHERE pl.order_no LIKE ? OR pl.payment_no LIKE ? OR p.name LIKE ?
            ORDER BY pl.created_at DESC 
            LIMIT 100";
    $paymentLogs = $db->query($sql, ["%{$searchKeyword}%", "%{$searchKeyword}%", "%{$searchKeyword}%"]);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>支付记录管理 - <?php echo htmlspecialchars(getSiteName()); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="assets/admin.css" rel="stylesheet">
    <style>
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .action-badge {
            font-size: 0.8em;
        }
        .search-form {
            max-width: 400px;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏（移动端显示） -->
    <div class="top-navbar d-flex align-items-center justify-content-between">
        <button class="sidebar-toggle">
            <i class="fas fa-bars"></i>
        </button>
        <h5 class="mb-0">支付记录 - <?php echo htmlspecialchars(getSiteName()); ?></h5>
        <div class="text-muted small">
            <i class="fas fa-user me-1"></i><?php echo htmlspecialchars($_SESSION['admin_username']); ?>
        </div>
    </div>

    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h4 class="mb-3">
                <i class="fas fa-cogs me-2"></i><span><?php echo htmlspecialchars(getSiteName()); ?></span>
            </h4>
            <p class="text-muted mb-0 small">欢迎, <?php echo htmlspecialchars($_SESSION['admin_username']); ?></p>
        </div>
        
        <nav class="nav flex-column">
            <a href="index.php" class="nav-link" data-tooltip="仪表盘">
                <i class="fas fa-tachometer-alt"></i><span>仪表盘</span>
            </a>
            <a href="products.php" class="nav-link" data-tooltip="商品管理">
                <i class="fas fa-box"></i><span>商品管理</span>
            </a>
            <a href="cdks.php" class="nav-link" data-tooltip="CDK管理">
                <i class="fas fa-gift"></i><span>CDK管理</span>
            </a>
            <a href="orders.php" class="nav-link" data-tooltip="订单管理">
                <i class="fas fa-shopping-cart"></i><span>订单管理</span>
            </a>
            <a href="payments.php" class="nav-link active" data-tooltip="支付记录">
                <i class="fas fa-credit-card"></i><span>支付记录</span>
            </a>
            <a href="settings.php" class="nav-link" data-tooltip="系统设置">
                <i class="fas fa-cog"></i><span>系统设置</span>
            </a>
            <a href="logout.php" class="nav-link" data-tooltip="退出登录">
                <i class="fas fa-sign-out-alt"></i><span>退出登录</span>
            </a>
        </nav>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 页面标题 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="fas fa-credit-card me-2"></i>支付记录管理
            </h2>
            <div class="text-muted">
                <i class="fas fa-calendar me-2"></i><?php echo date('Y年m月d日 H:i:s'); ?>
            </div>
        </div>

                <!-- 统计卡片 -->
                <div class="row">
                    <div class="col-md-3">
                        <div class="stat-card">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6>总支付记录</h6>
                                    <h3><?php echo $paymentStats['total_payments'] ?? 0; ?></h3>
                                </div>
                                <i class="fas fa-list fa-2x opacity-50"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6>唯一订单</h6>
                                    <h3><?php echo $paymentStats['unique_orders'] ?? 0; ?></h3>
                                </div>
                                <i class="fas fa-shopping-cart fa-2x opacity-50"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6>创建请求</h6>
                                    <h3><?php echo $paymentStats['create_count'] ?? 0; ?></h3>
                                </div>
                                <i class="fas fa-plus fa-2x opacity-50"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-card" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6>回调通知</h6>
                                    <h3><?php echo $paymentStats['notify_count'] ?? 0; ?></h3>
                                </div>
                                <i class="fas fa-bell fa-2x opacity-50"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 搜索表单 -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form method="GET" class="search-form">
                            <div class="input-group">
                                <input type="text" name="search" class="form-control" placeholder="搜索订单号、支付号或商品名称..." value="<?php echo htmlspecialchars($searchKeyword); ?>">
                                <button class="btn btn-primary" type="submit">
                                    <i class="fas fa-search"></i> 搜索
                                </button>
                                <?php if ($searchKeyword): ?>
                                    <a href="payments.php" class="btn btn-outline-secondary">
                                        <i class="fas fa-times"></i> 清除
                                    </a>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- 支付记录表格 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-list"></i>
                            支付记录列表
                        </h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($paymentLogs)): ?>
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle"></i>
                                暂无支付记录
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>订单号</th>
                                            <th>支付号</th>
                                            <th>操作类型</th>
                                            <th>金额</th>
                                            <th>商品</th>
                                            <th>联系信息</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($paymentLogs as $log): ?>
                                            <tr>
                                                <td><?php echo $log['id']; ?></td>
                                                <td>
                                                    <code><?php echo htmlspecialchars($log['order_no']); ?></code>
                                                </td>
                                                <td>
                                                    <?php if ($log['payment_no']): ?>
                                                        <code><?php echo htmlspecialchars($log['payment_no']); ?></code>
                                                    <?php else: ?>
                                                        <span class="text-muted">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php
                                                    $badgeClass = 'secondary';
                                                    if ($log['action'] === 'create') $badgeClass = 'primary';
                                                    if ($log['action'] === 'notify') $badgeClass = 'success';
                                                    if ($log['action'] === 'return') $badgeClass = 'info';
                                                    ?>
                                                    <span class="badge bg-<?php echo $badgeClass; ?> action-badge">
                                                        <?php echo strtoupper($log['action']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <?php if ($log['amount']): ?>
                                                        <strong>¥<?php echo number_format($log['amount'], 2); ?></strong>
                                                    <?php else: ?>
                                                        <span class="text-muted">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($log['product_name']): ?>
                                                        <?php echo htmlspecialchars($log['product_name']); ?>
                                                    <?php else: ?>
                                                        <span class="text-muted">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($log['contact_info']): ?>
                                                        <?php echo htmlspecialchars(substr($log['contact_info'], 0, 20)); ?>...
                                                    <?php else: ?>
                                                        <span class="text-muted">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php echo date('Y-m-d H:i:s', strtotime($log['created_at'])); ?>
                                                </td>
                                                <td>
                                                    <button class="btn btn-sm btn-outline-primary" 
                                                            data-bs-toggle="modal" 
                                                            data-bs-target="#logDetailModal" 
                                                            data-log='<?php echo json_encode($log); ?>'>
                                                        <i class="fas fa-eye"></i> 详情
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 日志详情模态框 -->
    <div class="modal fade" id="logDetailModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">支付记录详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="logDetailContent">
                        <!-- 动态内容 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="assets/admin.js"></script>
    <script>
        // 显示日志详情
        document.addEventListener('DOMContentLoaded', function() {
            const modal = document.getElementById('logDetailModal');
            modal.addEventListener('show.bs.modal', function(event) {
                const button = event.relatedTarget;
                const logData = JSON.parse(button.getAttribute('data-log'));
                
                const content = `
                    <div class="row">
                        <div class="col-md-6">
                            <h6>基本信息</h6>
                            <table class="table table-sm">
                                <tr>
                                    <td><strong>ID:</strong></td>
                                    <td>${logData.id}</td>
                                </tr>
                                <tr>
                                    <td><strong>订单号:</strong></td>
                                    <td><code>${logData.order_no}</code></td>
                                </tr>
                                <tr>
                                    <td><strong>支付号:</strong></td>
                                    <td>${logData.payment_no || '-'}</td>
                                </tr>
                                <tr>
                                    <td><strong>操作类型:</strong></td>
                                    <td><span class="badge bg-primary">${logData.action.toUpperCase()}</span></td>
                                </tr>
                                <tr>
                                    <td><strong>金额:</strong></td>
                                    <td>${logData.amount ? '¥' + parseFloat(logData.amount).toFixed(2) : '-'}</td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6>关联信息</h6>
                            <table class="table table-sm">
                                <tr>
                                    <td><strong>商品:</strong></td>
                                    <td>${logData.product_name || '-'}</td>
                                </tr>
                                <tr>
                                    <td><strong>联系信息:</strong></td>
                                    <td>${logData.contact_info || '-'}</td>
                                </tr>
                                <tr>
                                    <td><strong>创建时间:</strong></td>
                                    <td>${new Date(logData.created_at).toLocaleString()}</td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    <div class="mt-3">
                        <h6>请求参数</h6>
                        <pre class="bg-light p-3 border rounded" style="max-height: 200px; overflow: auto;">${logData.params ? JSON.stringify(JSON.parse(logData.params), null, 2) : '无参数'}</pre>
                    </div>
                `;
                
                document.getElementById('logDetailContent').innerHTML = content;
            });
        });
    </script>
</body>
</html>
